package com.anysoft.web;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;

import com.anysoft.R;
import com.anysoft.base.BaseActivity;
import com.anysoft.bean.QueryFundListBean;
import com.anysoft.event.TimeOutEvent;
import com.anysoft.utils.HttpUtils;
import com.anysoft.utils.MentorLogger;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.anysoft.HostConstant.HOST_WEB_URL_HEADER;
import static com.anysoft.R.id.tv_back;

/**
 * Created by wwq on 2017/3/10.
 */

//TODO 测试界面，没有用，上线删除
public class WebActivity extends BaseActivity {

    @BindView(tv_back)
    TextView tvBack;
    @BindView(R.id.tv_finish)
    TextView tvFinish;
    @BindView(R.id.wv)
    WebView webView;

    private String loadUrl;
    private String currentPage;

    private QueryFundListBean.DataBean bean;

    private String fundcode;
    private String fundname;
    private String fundType;
    private String titleStr;
    private String subTitleStr;
    private String fundstateid;
    private String token = "";
    private String param, url_title;

    private HashMap<String, String> urlParam;

    public Intent mIntent = new Intent();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_webview);
        ButterKnife.bind(this);
        fundcode = getIntent().getStringExtra("fundCode");
        fundname = getIntent().getStringExtra("fundName");
        fundType = getIntent().getStringExtra("fundType");
        titleStr = getIntent().getStringExtra("mainTitle");
        subTitleStr = getIntent().getStringExtra("subTitle");
        fundstateid = getIntent().getStringExtra("fundstateid");
        url_title = getIntent().getStringExtra("url_title");
        param = getIntent().getStringExtra("param");
        urlParam = processParam(param);
        initView();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    private void initView() {
//        loadUrl = getIntent().getStringExtra("url");
//        initUrl(url_title, param);
//        initUrl("fundDetail", HttpUtils.getCommonParams2StringByWeb(mActivity) + "&fundCode=" + fundcode + "&fundName=" + fundname
//                + "&cusNo=" + getFundCustomerNo() + "&fundstateid=" + fundstateid + "&fundType=" + fundType);
        initUrl("fundDetail", HttpUtils.getCommonParams2StringByWeb(mActivity) + "&fundCode=" +
                        fundcode + "&fundName=" + fundname + "&cusNo=" + getFundCustomerNo() + "&fundstateid=" +
                fundstateid + "&fundType=" + fundType);
//        loadUrl = "http://news.windin.com/ns/bulletin.php?id=77002816&type=1&code=26457b613f60";
//        loadUrl = "file:///android_asset/html/registrationProcess.html";
//        loadUrl += "token=" + mentorApplication.userBean.getToken() + "&merchantId=GY&channel=3&version=0.0.1&fundCode=" + bean.getFundcode() + "&cusNo=" + mentorApplication.userBean.getFundCustomerNo();
//        loadUrl = "http://www.icbccs.com.cn/";
//        loadUrl = "http://172.18.10.61:8080/GY_H5/icbcFund/searchTrade.html?isFromApp=true&merchantId=GY&channel=1&user_type=p&token=130f1610-bd36-402b-a9bb-3851d5a25f5e&version=1.0&uuid=D41D8CD98F00B204E9800998ECF8427E&platform=Android&Mac=02:00:00:00:00:00&phone_type=unknown:Android%20SDK%20built%20for%20x86&appChannel=gongyinruixin&cusNo=480000003221";
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        //设置加载进来的页面自适应手机屏幕
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setLoadWithOverviewMode(true);
        webView.loadData(loadUrl, "text/html", "UTF-8");
        //支持屏幕缩放
//        webSettings.setSupportZoom(true);
//        webSettings.setBuiltInZoomControls(true);
//        //不显示webview缩放按钮
//        webSettings.setDisplayZoomControls(false);

        // WebView加载web资源
//        webView.loadUrl(loadUrl);
        // 覆盖WebView默认使用第三方或系统默认浏览器打开网页的行为，使网页用WebView打开
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                // 返回值是true的时候控制去WebView打开，为false调用系统浏览器或第三方浏览器
                onshouldOverrideUrlLoadingCallBack(view, url);
                //System.out.println("webView.getUrl()-----" +
//                         webView.getUrl());
                return true;
            }

            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
                return super.shouldInterceptRequest(view, url);
            }

            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
                return super.shouldInterceptRequest(view, request);
            }


            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
            }

            @Override
            public void doUpdateVisitedHistory(WebView view, String url, boolean isReload) {
                super.doUpdateVisitedHistory(view, url, isReload);
            }

            @Override
            public void onLoadResource(WebView view, String url) {
                super.onLoadResource(view, url);
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                currentPage = url;
                super.onPageStarted(view, url, favicon);
            }

        });

        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
                result.confirm();
                return true;
            }

            @Override
            public boolean onJsConfirm(WebView view, String url, String message, JsResult result) {
                return super.onJsConfirm(view, url, message, result);
            }

            @Override
            public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) {
                return super.onJsPrompt(view, url, message, defaultValue, result);
            }
        });
    }


    private void onshouldOverrideUrlLoadingCallBack(WebView view, String url) {
        String url_decode = null;
        try {
            url_decode = URLDecoder.decode(url, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        MentorLogger.Log(TAG, "url_decode=" + url_decode);
        if (url.contains("index.html")) {
            finish();
        }
    }

    public void initUrl(String action, String param) {
        loadUrl = HOST_WEB_URL_HEADER + action + ".html?isFromApp=true&" + param;
        MentorLogger.Log(TAG, "loadUrl=" + loadUrl);
    }

    @OnClick({R.id.tv_back, R.id.tv_finish})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_back:
                if (webView.canGoBack()) {
                    if (!TextUtils.isEmpty(currentPage) && currentPage.contains("personCenter")) {
                        finish();
                    }
                    webView.goBack();// 返回前一个页面
                } else {
                    finish();
                }
                break;
            case R.id.tv_finish:
                finish();
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack()) {
            if (!TextUtils.isEmpty(currentPage) && currentPage.contains("personCenter")) {
                finish();
            }
            webView.goBack();// 返回前一个页面
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onTimeOutCallBack(TimeOutEvent event) {
        if (event.isSuccess) {
            finish();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (webView != null) {
            webView.stopLoading(); //停止加载
            ((ViewGroup) webView.getParent()).removeView(webView); //把webview从视图中移除
            webView.removeAllViews(); //移除webview上子view
            webView.clearCache(true); //清除缓存
            webView.clearHistory(); //清除历史
            webView.destroy(); //销毁webview自身
        }
    }
}
